package cn.wygandwdn.core.registry.impl;

import cn.wygandwdn.common.enumeration.ErrorType;
import cn.wygandwdn.common.exception.RpcException;
import cn.wygandwdn.core.registry.ServiceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: WYG
 * @time: 2021/10/28 19:25
 */

public class ServiceProviderImpl implements ServiceProvider {

    private static final Logger log = LoggerFactory.getLogger(ServiceProviderImpl.class);

    private static final Map<String, Object> serviceMap = new ConcurrentHashMap<>();
    private static final Set<String> registeredService = ConcurrentHashMap.newKeySet();

    @Override
    public <T> void addService(T service, String serviceName) {
        if (registeredService.contains(serviceName)) {
            return;
        }
        registeredService.add(serviceName);
        serviceMap.put(serviceName, service);
        log.debug("向接口: {} 注册服务: {}", service.getClass().getInterfaces(), serviceName);
    }

    @Override
    public Object getService(String serviceName) {
        Object service = serviceMap.get(serviceName);
        if (service == null) {
            log.error("服务未进行注册");
            throw new RpcException(ErrorType.SERVICE_NOT_REGISTER);
        }
        return service;
    }
}
